package main

import (
	"code.google.com/p/go-modl/modlgen"
	l4g "code.google.com/p/log4go"
	"fmt"
	"github.com/jteeuwen/go-pkg-optarg"
	"os"
	"path/filepath"
)

func main() {
	defer l4g.Close()

	optarg.Header("General")
	optarg.Add("h", "help", "Print usage information", false)

	optarg.Header("Output Verbosity")
	optarg.Add("d", "debug", "Turn debug output on. This includes trace, info and warning output also", false)
	optarg.Add("t", "trace", "Turn trace output on. This includes info and warning output also", false)
	optarg.Add("i", "info", "Turn info output on. This include warning output also", false)
	optarg.Add("w", "warning", "Turn warning output on.", false)

	optarg.Header("Paths")
	optarg.Add("", "basedir", "The base directory of the project, the one containing the \"src\" directory under which the specified packages containing the \".sdo\" files are to be found", ".")

	optarg.Header("Packages")
	_, commandName := filepath.Split(os.Args[0])
	optarg.UsageInfo = fmt.Sprintf("Usage: %s [options] pkg1 pkg2 ...", commandName)

	var debug, trace, info, warning bool
	baseDir := "."

	for opt := range optarg.Parse() {
		switch opt.Name {
		case "help":
			optarg.Usage()
			os.Exit(0)
		case "debug":
			debug = true
		case "trace":
			trace = true
		case "info":
			info = true
		case "warning":
			warning = true

		case "basedir":
			baseDir = opt.String()
		}
	}

	configureLogging(debug, trace, info, warning)
	for _, srcPkgDir := range optarg.Remainder {
		srcPkgDir = filepath.Join(srcPkgDir, "") // remove trailing dir separator if it was specified
		if err := modlgen.Generate(baseDir, srcPkgDir); err != nil {
			l4g.Close()
			os.Exit(-1)
		}
	}
}

func configureLogging(debug, trace, info, warning bool) {
	l4g.Global["stdout"].Close()
	l4gLevel := l4g.CRITICAL
	switch {
	case debug:
		l4gLevel = l4g.DEBUG
	case trace:
		l4gLevel = l4g.TRACE
	case info:
		l4gLevel = l4g.INFO
	case warning:
		l4gLevel = l4g.WARNING
	}
	l4g.AddFilter("stdout", l4gLevel, l4g.NewFormatLogWriter(os.Stdout, "%M"))
}
